package com.service;

import com.sql.MySQLServiceGrpc;
import com.sql.SQLRequest;
import com.sql.SQLResponse;
import io.grpc.stub.StreamObserver;
import lombok.SneakyThrows;
import net.devh.boot.grpc.server.service.GrpcService;
import java.sql.*;

/**
 * @author 何永豪
 * @className MySQLService
 * @description TODO
 * @date 2023/10/31 17:00
 */
@GrpcService
public class MySQLService extends MySQLServiceGrpc.MySQLServiceImplBase {

    @SneakyThrows
    @Override
    public void executeSQL(SQLRequest request, StreamObserver<SQLResponse> responseObserver) {
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/xiaoshu?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&allowPublicKeyRetrieval=true",
                "root", "730730");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(request.getSql());
        // 处理SQL执行结果
        SQLResponse.Builder responseBuilder = SQLResponse.newBuilder();
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            String name = resultSet.getString("name");
            String age = resultSet.getString("age");
            String skill = resultSet.getString("skill");
            responseBuilder.addResult(id+"-"+name+"-"+age+"-"+skill);
        }
        // 发送结果给客户端
        responseObserver.onNext(responseBuilder.build());
        responseObserver.onCompleted();
    }

}